package com.sz.biz.logistics.base.service.impl;

import com.sz.biz.common.constants.ErrorCodes;
import com.sz.biz.common.constants.ModuleNames;
import com.sz.biz.logistics.base.entity.AirplaneModel;
import com.sz.biz.logistics.base.service.AirplaneModelService;
import com.sz.common.base.cache.EntityCache;
import com.sz.common.base.constants.AppDomain;
import com.sz.common.base.constants.UserActions;
import com.sz.common.base.dao.ParamData;
import com.sz.common.base.dto.QResultDto;
import com.sz.common.base.dto.QueryParams;
import com.sz.common.base.dto.ResultDto;
import com.sz.common.base.exception.Exceptions;
import com.sz.common.base.service.AbstractService;
import com.sz.common.base.service.I18nBaseService;
import com.sz.common.core.service.PrincipalLogUtils;
import com.sz.common.core.system.dto.FileInfoDto;
import com.sz.common.core.system.service.SysFileGroupService;
import com.sz.common.core.system.service.SysFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Function: AirplaneModelServiceImpl <br>
 * Author: Charles <br>
 * Date: 2016-12-01 15:05:00
 */
@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class AirplaneModelServiceImpl extends AbstractService implements AirplaneModelService {

    @Autowired
    I18nBaseService i18nService;
    @Autowired
    SysFileService fileService;

    @Autowired
    SysFileGroupService fileGroupService;

    @Override
    protected String getMapperNamespace() {
        return "com.sz.biz.logistics.base.entity.mapper.AirplaneModelMapper";
    }

    @Override
    public void refreshCache() {
        EntityCache.clearNamespace(getMapperNamespace());
    }

    /**
     * @param model       --机型实体
     * @param attachments --附件Id
     * @return new Id
     */
    @Override
    public Integer addAirplaneModel(AirplaneModel model, List<String> attachments) {
        if (model == null) {
            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "AirplaneModel");
        }
        if (!(StringUtils.hasLength(model.getIata())
                && StringUtils.hasLength(model.getName()))) {
            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "iata/name");
        }
        if (isIATAExist(model.getIata())) {
            throw Exceptions.bizException(ErrorCodes.ERROR_BIZ_AIRPLANEMODEL_IATA_EXIST, model.getIata());
        }

        if (attachments != null && attachments.size() > 0) { //update file
            String fileGroupId = fileGroupService.createFileGroup(attachments, "biz.airplane.model", null, AppDomain.OPERATION);
            model.setPicture(fileGroupId);
        }
        this.dao.save(getSqlName("insertSelective"), model);
        //保存操作日志
        Map<String, Object> dataBackup = new HashMap<>();
        dataBackup.put("ADD_AIRPLANE", model);
        PrincipalLogUtils.addOperationLog(ModuleNames.BIZ, ModuleNames.BIZ_AIRPLANE, UserActions.ADD, "新建机型", dataBackup);
        return model.getId();
    }

    /**
     * @param model --机型实体
     */
    @Override
    public void updateAirPlanModel(AirplaneModel model, List<String> attachments) {
        if (model == null) {
            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "AirplaneModel");
        }
        if (model.getId() <= 0
                || !StringUtils.hasLength(model.getName())
                || !StringUtils.hasLength(model.getIata())) {
            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "id/iata/name");
        }
        if (isIATAExist(model.getIata(), model.getId())) { // duplicate
            throw Exceptions.bizException(ErrorCodes.ERROR_BIZ_AIRPLANEMODEL_IATA_EXIST, model.getIata());
        }
        String fileGroupId = fileGroupService.saveFileToGroup(model.getPicture(), attachments,
                "biz.airplane.model", null, AppDomain.OPERATION);
        model.setPicture(fileGroupId);

        this.dao.save(getSqlName("updateByPrimaryKeySelective"), model);
        //保存操作日志
        Map<String, Object> dataBackup = new HashMap<>();
        dataBackup.put("UPDATE_AIRPLANE", model);
        PrincipalLogUtils.addOperationLog(ModuleNames.BIZ, ModuleNames.BIZ_AIRPLANE, UserActions.UPDATE, "修改机型", dataBackup);
    }

    /**
     * 获取单条model数据
     *
     * @param id --model id
     * @return --机型实体
     */
    @Override
    public AirplaneModel getById(int id) {
        AirplaneModel model = (AirplaneModel) this.dao.findForObject(getSqlName("selectByPrimaryKey"), id);
        return model;
    }

    /**
     * 删除
     *
     * @param ids --机型Id
     */
    @Override
    public void deleteByIds(List<Integer> ids) {
        if (ids != null && ids.size() > 0) {
            this.i18nService.deleteByRefIds("biz_airplane_model_i18n", ids);
            this.dao.update(getSqlName("softDelete"), ids);
            //保存操作日志
            Map<String, Object> dataBackup = new HashMap<>();
            dataBackup.put("DELETE_AIRPLANE", ids);
            PrincipalLogUtils.addOperationLog(ModuleNames.BIZ, ModuleNames.BIZ_AIRPLANE, UserActions.DELETE, "删除机型", dataBackup);
        }
    }

    /**
     * @param iataCode --IATA code
     * @return --是否存在
     */
    @Override
    public boolean isIATAExist(String iataCode) {
        Integer count = (Integer) this.dao.findForObject(getSqlName("isIATAExist"), iataCode);
        return count != null && count > 0;
    }

    /**
     * @param iataCode --IATA code
     * @param exceptId --排除此Id
     * @return --是否存在
     */
    @Override
    public boolean isIATAExist(String iataCode, int exceptId) {
        AirplaneModel cmodel = this.getByIataCode(iataCode);
        return cmodel != null && !cmodel.getId().equals(exceptId) && !cmodel.getIsDeleted();
    }

    /**
     * @param icaoCode --ICAO code
     * @return --是否存在
     */
    public boolean isICAOExist(String icaoCode) {
        Integer count = (Integer) this.dao.findForObject(getSqlName("isICAOExist"), icaoCode);
        return count != null && count > 0;
    }

    /**
     * @param iataCode --IATA code
     * @return --机型实体
     */
    public AirplaneModel getByIataCode(String iataCode) {
        return (AirplaneModel) this.dao.findForObject(getSqlName("getByIATA"), iataCode);
    }

    /**
     * @param params --页面参数
     * @return --机型列表
     */
    @Override
    public ResultDto getAirplaneModels(QueryParams params) {
        ParamData paras = this.convertQueryParams(params);
        List<AirplaneModel> list = this.dao.findForList(getSqlName("selectWithDefaultListPage"), paras, AirplaneModel.class);
        QResultDto result = new QResultDto(list, paras.getPagination());
        return result;
    }

    @Override
    public ResultDto getShortAirplaneModels(QueryParams queryParams) {
        ParamData paras = this.convertQueryParams(queryParams);
        List<AirplaneModel> list = this.dao.findForList(getSqlName("selectWithShortListPage"), paras, AirplaneModel.class);
        QResultDto result = new QResultDto(list, paras.getPagination());
        return result;
    }

    /**
     * @param params --页面参数
     * @return --数据DTO
     */
    @Override
    public ResultDto getAirplaneModelsWithI18n(QueryParams params) {
        ParamData paras = this.convertQueryParams(params);
        List<Map> list = this.dao.findForList(getSqlName("selectWithLangListPage"), paras, Map.class);
        QResultDto result = new QResultDto(list, paras.getPagination());
        return result;
    }

    /**
     * @param fileGroupId --model Id
     * @return
     */
    @Override
    public List<FileInfoDto> getAttachments(String fileGroupId) {
        return fileGroupService.getFileDtosByGroupId(fileGroupId);
    }
}
